import React, { useState } from 'react';
import {
  Form,
  Input,
  Button,
  Card,
  Typography,
  Space,
  message,
  Checkbox,
  Divider,
  Table,
  Tag,
  Collapse,
} from 'antd';
import {
  UserOutlined,
  LockOutlined,
  TeamOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  InfoCircleOutlined,
} from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';

const { Title, Text } = Typography;
const { Panel } = Collapse;

const Login = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const history = useHistory();
  const { login, getAllMembers } = useAuth();

  // 获取可用的账号信息
  const availableAccounts = getAllMembers().filter(member => member.accountStatus === 'active');

  const onFinish = async (values) => {
    setLoading(true);
    try {
      // 模拟登录API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 这里可以添加实际的登录逻辑
      const success = await login(values.username, values.password);
      
      if (success) {
        message.success('登录成功！');
        history.push('/');
      } else {
        message.error('用户名或密码错误！');
      }
    } catch (error) {
      message.error('登录失败，请重试！');
    } finally {
      setLoading(false);
    }
  };

  const handleQuickLogin = async (username, password, name) => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      const success = await login(username, password);
      if (success) {
        message.success(`${name} 登录成功！`);
        history.push('/');
      }
    } catch (error) {
      message.error('登录失败，请重试！');
    } finally {
      setLoading(false);
    }
  };

  const accountColumns = [
    {
      title: '成员',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <span>{text}</span>
          <Tag color="blue">{record.role}</Tag>
        </Space>
      ),
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '账号角色',
      dataIndex: 'accountRole',
      key: 'accountRole',
      render: (role) => (
        <Tag color={role === 'admin' ? 'purple' : 'blue'}>
          {role === 'admin' ? '管理员' : '普通用户'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="link"
          size="small"
          onClick={() => handleQuickLogin(record.username, record.password, record.name)}
          disabled={loading}
        >
          快速登录
        </Button>
      ),
    },
  ];

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px'
    }}>
      <Card
        style={{
          width: '100%',
          maxWidth: 500,
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
          borderRadius: 12,
        }}
      >
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <TeamOutlined style={{ fontSize: 48, color: '#1890ff', marginBottom: 16 }} />
          <Title level={2} style={{ margin: 0, color: '#1890ff' }}>
            乐队管理系统
          </Title>
          <Text type="secondary">请登录您的账户</Text>
        </div>

        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名！' },
              { min: 3, message: '用户名至少3个字符！' }
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
              autoComplete="username"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码！' },
              { min: 6, message: '密码至少6个字符！' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              autoComplete="current-password"
              iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
            />
          </Form.Item>

          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>

            <a style={{ float: 'right' }} href="#forgot">
              忘记密码？
            </a>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              style={{ width: '100%', height: 48, fontSize: 16 }}
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        <Divider>或者</Divider>

        {/* 可用账号信息 */}
        <Collapse 
          ghost 
          style={{ marginBottom: 16 }}
          expandIconPosition="end"
        >
          <Panel 
            header={
              <Space>
                <InfoCircleOutlined />
                <span>查看可用账号</span>
              </Space>
            } 
            key="accounts"
          >
            <div style={{ marginBottom: 16 }}>
              <Text type="secondary">
                以下是系统中可用的账号，您可以使用任意一个进行登录：
              </Text>
            </div>
            <Table
              columns={accountColumns}
              dataSource={availableAccounts}
              pagination={false}
              size="small"
              rowKey="id"
            />
            <div style={{ marginTop: 16, textAlign: 'center' }}>
              <Text type="secondary">
                默认密码：password123
              </Text>
            </div>
          </Panel>
        </Collapse>

        <div style={{ marginTop: 16, textAlign: 'center' }}>
          <Text type="secondary">
            还没有账户？请联系管理员创建账号
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default Login; 